<?php namespace App\Admin\Access\Role\Listeners;

use App\Core\Repository\Criterias\FixedCriteria;

use App\Core\Service\Listeners\DeleteListener as Base;
use App\Admin\Access\Role\Repository as RoleRepository;

class DeleteListener extends Base {
    
    public function onDeleteSaved(){
        foreach($this->service->deleteModels as $model){
            with(new RoleRepository())->addCriteria(new FixedCriteria('parent_id', $model->role_id))->delete();
            if($model->parent_id > '0'){
                $parentModel = $this->service->repository->resetQuery()->resetCriteria(true)->addCriteria(
                    new FixedCriteria('role_id', $model->parent_id)
                    )->first();
                if($parentModel){ 
                    $newCount = intval($parentModel->sub_count) - 1;
                    $this->service->repository->resetQuery()->resetCriteria(true)->addCriteria(
                        new FixedCriteria('role_id', $parentModel->role_id)
                        )->update(['sub_count' => $newCount]);
                }
            }   
        }
    }
}